package com.jerry.provider.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jerry.common.bean.User;
import com.jerry.provider.service.UserService;

@RestController
@RefreshScope
@RequestMapping("/user")
public class UserController {

	@Value("${from}")
	private String from;

	@GetMapping("/from")
	public String from() {
		return this.from;
	}

	@Autowired
	private UserService userService;
	@Autowired
	private DiscoveryClient client;

	//查询用户列表
	@GetMapping("/list")
	public List<User> list() {
		ServiceInstance instance = client.getLocalServiceInstance();
		List<User> userList = userService.list();
		for (User user : userList) {
			user.setHost(instance.getHost());
			user.setPort(instance.getPort());
			user.setServerId(instance.getServiceId());
			System.out.println("provider === user === "+user);
		}
		return userList;
	}
	
	//根据id查询用户
	@GetMapping("/get/{id}")
	public User get(@PathVariable("id") Long id) {
		ServiceInstance instance = client.getLocalServiceInstance();
		User user = userService.get(id);
		user.setHost(instance.getHost());
		user.setPort(instance.getPort());
		user.setServerId(instance.getServiceId());
		System.out.println("provider === user === "+user);
		return user;
	}
	
	//增加用户
	@PostMapping("/add")
	public boolean add(@RequestBody User user) {
		return userService.add(user);
	}

	//更新用户
	@PostMapping("/update")
	public boolean update(@RequestBody User user) {
		return userService.update(user);
	}

	//删除用户
	@DeleteMapping("/delete/{id}")
	public void delete(@PathVariable("id") Long id) {
		userService.delete(id);
	}



}
